<script>
import {
  addUser,
  deleteUser,
  queryOrganization,
  queryRole,
  queryUser,
  queryUserByUserId, updateUser
} from "@/api/systemAdministration/user/user";
import {
  addDepartment,
  updateDepartment
} from "@/api/systemAdministration/organizationalStructureManagement/organizationalStructure";

function setNodeLevel(node, level) {
  node.level = level; // 首先设置当前节点的层级
  if (node.departments) { // 如果当前节点有子节点
    node.departments.forEach(child => setNodeLevel(child, level + 1)); // 递归地为子节点设置层级
  }
}

// 定义转换函数
function transformData(backendData) {
  return backendData.map(item => {
    let node;
    if(item.level === 1){
      node = {
        value: item.orgID, // 使用后端数据中的id作为value
        label: item.orgName, // 使用后端数据中的name作为label
      };
    }else if(item.level === 2){
      node = {
        value: item.deptID, // 使用后端数据中的id作为value
        label: item.deptName, // 使用后端数据中的name作为label
      };
    }
    // 如果有子级数据，递归转换
    if (item.departments && item.departments.length) {
      node.children = transformData(item.departments);
    }
    return node;
  });
}
function transformData123(backendData) {
  backendData.organizationStructure = {departmentss:{deptID:backendData.organizationStructure[1]}}
  backendData.roles = {roleID:backendData.roles}
}

let logo;
export default {
  name: "index",
  data() {
    return {
      title:"",//窗口标题
      tableData:[],//table数据
      total:0,//总数量
      pageNum:1,//当前页
      pageSize:5,//每页显示数量
      pages:0, //总页数
      user:{},
      dialogFormVisible: false, // 窗口显示
      //修改数据
      Form:{
        userID: null,
        userName: '',
        password: '',
        realName: '',
        title: '',
        leadershipStatus: false,
        gender: '',
        status: 1,
        roles: {}, // 假设 Roles 是一个对象
        department: {}, // 假设 Department 是一个对象
        organizationStructure: {} // 假设 Organizationstructure 是一个对象
      },
      //组织部门
      organizationalUnits:[],
      //角色
      role:[],
      rules:{
        userName: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 3, max: 15, message: '登录名长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '真实姓名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        organizationStructure: [
          { required: true, message: '请选择所在部门', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请选择职称', trigger: 'blur' }
        ],
        roles: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getData();
  },
  methods:{
    //获取用户数据
    getData: function() {
      queryUser(this.pageNum, this.pageSize, this.user)
        .then((data) => {
          if(data.code === 200){
            this.tableData = data.data.list;
            this.total = data.data.total;
            this.pages = data.data.pages;
          }
        })
        .catch((error) => {
          console.log(error);
        })
    },
    //分页切换显示数量时调用的方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    //分页切换页面时调用的方法
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getData();
    },
    //新增
    handleAdd(){
      logo = "add"
      this.$refs.FormRef.clearValidate()
      this.title = "新增用户信息"
      //查询角色
      queryRole()
        .then((data) => {
          if(data.code === 200){
            this.role = data.data
          }
        })
        .catch((error) =>{
          console.log(error);
        })
      //查询组织和部门
      queryOrganization()
        .then((data) => {
          if(data.code === 200){
            data.data.forEach(node =>  setNodeLevel(node, 1));
            this.organizationalUnits = transformData(data.data)
          }
        })
        .catch((error) => {
          console.log(error)
        })
      this.dialogFormVisible = true;
    },
    //修改
    handleEdit(row){
      logo = "update"
      this.$refs.FormRef.clearValidate()
      this.title = "修改用户信息"
      //查询用户信息
      queryUserByUserId(row.userID)
        .then((data) => {
          if(data.code === 200){
            this.Form = data.data
          }
        })
        .catch((error) => {
          console.log(error)
        })
      //查询角色
      queryRole()
        .then((data) => {
          if(data.code === 200){
            this.role = data.data
          }
        })
        .catch((error) =>{
          console.log(error);
        })
      //查询组织和部门
      queryOrganization()
        .then((data) => {
          if(data.code === 200){
            data.data.forEach(node =>  setNodeLevel(node, 1));
            this.organizationalUnits = transformData(data.data)
          }
        })
        .catch((error) => {
          console.log(error)
        })
      this.dialogFormVisible = true;
    },
    //删除
    handleDelete(row){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.userID)
          .then((data) =>{
            if(data.code === 200){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getData();
            }
          })
          .catch((error) =>{
            console.log(error);
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //新增
    onSubmit(){
      this.$refs.FormRef.validate((valid) => {
        if (!valid) {
          this.$message.warning('兄嘚按规矩办事！！')
          return false
        } else {
          transformData123(this.Form);
          if (logo === "update") {
            updateUser(this.Form)
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: '修改成功！！',
                    type: 'success'
                  });
                  this.dialogFormVisible = !this.dialogFormVisible;
                  this.getData();
                } else {
                  this.$message.error('修改失败!!');
                }
              })
              .catch((error) => {
                console.log(error);
              });
          } else if (logo === "add") {
            addUser(this.Form)
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: '新增成功！！',
                    type: 'success'
                  });
                  this.dialogFormVisible = !this.dialogFormVisible;
                  this.getData();
                } else {
                  this.$message.error('新增失败!!');
                }
              })
              .catch((error) => {
                console.log(error);
              });
          }
        }
      })
    }
  }
}
</script>

<template>
  <div style="margin-top: 20px">
    <el-form :inline="true" :model="user" label-width="auto">
      <el-form-item label="用户名：" >
        <el-input v-model="user.userName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="真实姓名：">
        <el-input v-model="user.realName" placeholder="请输入真实姓名" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getData">查询</el-button>
      </el-form-item>
      <el-button style="float: right;margin-right: 50px" @click="handleAdd">新增</el-button>
    </el-form>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        align="center"
        type="index"
        label="排序">
      </el-table-column>
      <el-table-column
        prop="userName"
        align="center"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="realName"
        align="center"
        label="真实姓名">
      </el-table-column>
      <el-table-column
        prop="roles.roleName"
        align="center"
        label="角色">
      </el-table-column>
      <el-table-column
        align="center"
        label="机构/部门">
        <template slot-scope="scope">
          {{scope.row.organizationStructure.orgName}}/
          {{scope.row.organizationStructure.departmentss.deptName}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="状态">
        <template slot-scope="scope">
          <p v-if="scope.row.status === 1">可用</p>
          <p v-else-if="scope.row.status === 0">冻结</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 20, 50, 100]"
      :page-size="pageSize"
      style="text-align: center;"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--    修改窗口-->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      center
    >
      <el-form
        :model="Form"
        ref="FormRef"
        :rules="rules"
        status-icon
        style="margin-left: 100px">
        <el-form-item label="登录名：" label-width="120px" prop="userName">
          <el-input class="updateDialogFormStyle" v-model="Form.userName"/>
        </el-form-item>
        <el-form-item label="密    码：" label-width="120px" prop="password">
          <el-input class="updateDialogFormStyle" v-model.number="Form.password"/>
        </el-form-item>
        <el-form-item label="真实姓名：" label-width="120px" prop="realName">
          <el-input class="updateDialogFormStyle" v-model="Form.realName"/>
        </el-form-item>
        <el-form-item label="所在部门：" label-width="120px" prop="organizationStructure">
          <el-cascader
            class="updateDialogFormStyle"
            :options="organizationalUnits"
            v-model="Form.organizationStructure"
          >
<!--            <template slot-scope="{ node, data }">-->
<!--              <span>{{ data.orgName || data.deptName }}</span>-->
<!--            </template>-->
          </el-cascader>
        </el-form-item>
        <el-form-item label="性别：" label-width="120px" prop="gender">
          <el-radio-group class="updateDialogFormStyle"  v-model="Form.gender">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职位：" label-width="120px" prop="title">
          <el-select class="updateDialogFormStyle"  v-model="Form.title">
            <el-option label="请选择职称" :value="null"/>
            <el-option label="总经理" value="总经理"/>
            <el-option label="总监" value="总监"/>
            <el-option label="助理" value="助理"/>
            <el-option label="部门经理" value="部门经理"/>
            <el-option label="普通职员" value="普通职员"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" label-width="120px" prop="roles">
          <el-select class="updateDialogFormStyle"  v-model="Form.roles" placeholder="请选择" >
            <el-option label="请选择" :value="0"/>
            <el-option v-for="item in role" :key="item.roleID" :label="item.roleName" :value="item.roleID" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" label-width="120px" prop="status">
          <el-radio-group class="updateDialogFormStyle"  v-model="Form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.updateDialogFormStyle{
  width: 250px;
}
.el-dialog{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
